import json
import datetime

from bson.objectid import ObjectId

from api_base import *


class APIDiscussHandler(APIBaseHandler):
    @check_role(RoleStudent)
    async def get(self):
        '''
        获取讨论
        '''
        labidstr = get_id(self.request.uri)
        skip = 0
        limit = 0
        sort = 1
        try:
            skip = int(self.get_argument('skip'))
            limit = int(self.get_argument('limit'))
            sort = int(self.get_argument('sort'))
        except:
            pass
        discuss = []
        async for item in self.db.discussions.find({'labid': labidstr}).sort([('topicid', sort), ('time', 1)]).limit(limit).skip(skip):
            item['_id'] = str(item['_id'])
            item['time'] = item['time'].timestamp()
            discuss.append(item)
        self.write_json(discuss)

    @check_role(RoleStudent)
    async def post(self):
        '''
        发表讨论
        '''
        labidstr = get_id(self.request.uri)
        try:
            js = json.loads(self.request.body)
            ref = js['ref']
            data = js['data']
        except:
            self.write_json({'info': 'json_error'})
            return
        if ref < 0:
            topicid = await self.db.discussions.count_documents({'labid': labidstr})
        else:
            topicid = ref
        await self.db.discussions.insert_one(
            {
                'labid': labidstr,
                'topicid': topicid,
                'from': self.current_user,
                'ref': ref,
                'data': data,
                'time': datetime.datetime.now()
            })
        self.write_json({'info': 'ok', 'topicid': topicid})
